package jmind.core.jdbc;

import javax.sql.DataSource;

import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;

public class JdbcFactory {

    private AbstractXmlApplicationContext context = null;
    //private XmlBeanFactory context2 = null;

    private static volatile JdbcFactory factory = null;

    public static JdbcFactory getFactory() {

        if (factory == null) {
            factory = new JdbcFactory();
        }

        return factory;
    }

    private JdbcFactory() {
        /**
        String path = System.getProperty("user.dir") + File.separator + "src" + File.separator + "main"
        		+ File.separator + "webapp" + File.separator + "WEB-INF" + File.separator + "spring" + File.separator
        		+ "jdbc-config.xml";
        context = new FileSystemXmlApplicationContext(path);
        context2 = new XmlBeanFactory(new FileSystemResource(path));
        **/
        String path = "jdbc-config.xml";
        context = new ClassPathXmlApplicationContext(path);

    }

    public Object getBean(String source) {
        return context.getBean(source);
    }

    private DataSource getDataSource(String source) {
        return (DataSource) context.getBean(source);
    }

    public JdbcTemplate getJdbc(String source) {

        JdbcTemplate jdbc = new JdbcTemplate(getDataSource(source));

        return jdbc;
    }

    // SimpleJdbcInsertOperations
    public SimpleJdbcInsert getSimpleJdbcInsert(String source) {

        SimpleJdbcInsert jdbc = new SimpleJdbcInsert(getDataSource(source));

        return jdbc;
    }

    public NamedParameterJdbcTemplate getNameJdbc(String source) {

        NamedParameterJdbcTemplate jdbc = new NamedParameterJdbcTemplate(getDataSource(source));

        return jdbc;
    }

}
